<script setup lang="ts">
import {
  Viewer,
  UrlTemplateImageryProvider,
  ImageryLayer,
  Cartesian3,
  Math,
  PlaneGeometry,
  EllipsoidSurfaceAppearance,
  RectangleGeometry,
  Rectangle,
  GeometryInstance,
  Primitive,
  Material,
  Color,
  MaterialProperty,
  Event,
  JulianDate,
  Property,
} from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import { gsap } from 'gsap'
import { onMounted, ref } from 'vue'
;(window as any).CESIUM_BASE_URL = '/cesium'

const contentRef = ref<HTMLDivElement>()

onMounted(() => {
  const viewer = new Viewer(contentRef.value!, {
    infoBox: false,
    /** 搜索框 */
    geocoder: false,
    /** home按钮 */
    homeButton: false,
    // 动画控件
    animation: false,
    // 全屏按钮
    fullscreenButton: false,
    // 场景模式选择器
    sceneModePicker: false,
    // 时间轴
    timeline: false,
    // 导航提示
    navigationHelpButton: false,
    // 地图选择器
    baseLayerPicker: false,
  })

  const layer = new ImageryLayer(
    new UrlTemplateImageryProvider({
      url: 'http://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
      minimumLevel: 1,
      maximumLevel: 18,
    }),
    {}
  )

  viewer.imageryLayers.add(layer)

  viewer.camera.setView({
    destination: Cartesian3.fromDegrees(116.398115, 39.907913, 9950000),
    orientation: {
      /** 相机朝向 */
      heading: Math.toRadians(0),
      /** 相机俯视角 */
      pitch: Math.toRadians(-90),
      /** 相机翻滚角 */
      roll: 0,
    },
  })

  const geometry = new RectangleGeometry({
    rectangle: Rectangle.fromDegrees(90, 20, 110, 30),
    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
  })

  const geoInstance = new GeometryInstance({
    id: 'test-geo',
    geometry: geometry,
  })

  const material = new Material({
    fabric: {
      type: 'MyOwnFabric',
      uniforms: {
        u_time: 0,
      },
      source: `
          uniform float u_time;
          czm_material czm_getMaterial(czm_materialInput materialInput){
            czm_material tempCzm = czm_getDefaultMaterial(materialInput);

            float strength = mod((materialInput.s + u_time) * 2., 1.0);

            tempCzm.diffuse = vec3(strength, 0.0, 0.0);
            tempCzm.alpha = 0.8;
            return tempCzm;
          }
          `,
    },
  })

  const appearance = new EllipsoidSurfaceAppearance({
    material: material,
  })

  const primitive = new Primitive({
    geometryInstances: geoInstance,
    appearance: appearance,
  })

  console.log(appearance.fragmentShaderSource)

  gsap.to(material.uniforms, { u_time: 10, duration: 5, repeat: -1 })

  viewer.scene.primitives.add(primitive)
})
</script>

<template>
  <div class="fabric-test" ref="contentRef"></div>
</template>

<style lang="scss" scoped>
.fabric-test {
  height: 100%;
  width: 100%;
}
</style>
